package com.lscl.rabbitmq.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * 测试消息确认机制中的事务
 */
//@Configuration
public class Config_03_Transaction {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        // 开启rabbitmq对事物的支持
        rabbitTemplate.setChannelTransacted(true);

        // 消息不可达时进行消息回退
        rabbitTemplate.setMandatory(true);
    }

    /**
     * 注入RabbitMQ事务管理器
     *
     * @param
     * @return
     */
    @Bean
    public RabbitTransactionManager rabbitTransactionManager() {

        RabbitTransactionManager manager = new RabbitTransactionManager();
        ConnectionFactory factory = rabbitTemplate.getConnectionFactory();
        manager.setConnectionFactory(factory);

        return manager;
    }
}
